﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

// 基于UI的多点(2点)触控
public class TouchUIMul : MonoBehaviour
{
    TouchEx _touch;
    // 触摸点信息
    List<PointerEventData> _touchPointsData = new List<PointerEventData>();
    // 当前帧内拖动了的点信息
    List<PointerEventData> _draggingData = new List<PointerEventData>();

    // 上一次的两点距离，用于计算delta
    float _lastDis;

    void Awake()
    {
        Init();
    }

    public void Init()
    {
        _touch = gameObject.AddComponent<TouchEx>();
        _touch.OnPointerDownCallback += touchDown;
        _touch.OnPointerUpCallback += touchUp;
        _touch.OnDragCallback += onDrag;
    }

    private void onDrag(PointerEventData ped)
    {
        // 非有效拖动点
        if (_touchPointsData.IndexOf(ped) < 0) { return; }

        _draggingData.Add(ped);
    }

    private void touchUp(PointerEventData ped)
    {
        _touchPointsData.Remove(ped);
    }

    private void touchDown(PointerEventData ped)
    {
        // 仅支持2点触控
        if (_touchPointsData.Count > 1) { return; }

        _touchPointsData.Add(ped);

        // 刚刚够2点
        if (_touchPointsData.Count > 1)
        {
            _lastDis = Vector2.Distance(_touchPointsData[0].position, _touchPointsData[1].position);
        }
    }

    void Update()
    {
        if (_touchPointsData.Count <= 0) { return; }

        // 多点触控
        if (_touchPointsData.Count > 1)
        {
            LoopMulTouch();
            _draggingData.Clear();
            return;
        }
        _draggingData.Clear();
    }

    // 多点触控，循环
    void LoopMulTouch()
    {
        // 若无拖动点，说明本帧无操作
        if (_draggingData.Count == 0){ return; }

        // 若有拖动点但拖动数量不足，则补充不动点进入后续计算
        if (_draggingData.Count < _touchPointsData.Count)
        {
            foreach (var touchData in _touchPointsData)
            {
                if (_draggingData.IndexOf(touchData) < 0)
                {
                    _draggingData.Add(touchData);
                }
            }
        }

        if (_draggingData.Count < 2)
        {
            Debug.Log("多点触控，仅有" + _draggingData.Count);
            return;
        }

        // 开始计算2点触控操作
        var curDis = Vector2.Distance(_draggingData[0].position, _draggingData[1].position);
        var delta = (curDis - _lastDis);

        _lastDis = curDis;
    }
}
